Skip to content

Method: setFieldValue(Field, Object)

1: /**
2: * Copyright (C) 2020 Czech Technical University in Prague
3: *
4: * This program is free software: you can redistribute it and/or modify it under
5: * the terms of the GNU General Public License as published by the Free Software
6: * Foundation, either version 3 of the License, or (at your option) any
7: * later version.
8: *
9: * This program is distributed in the hope that it will be useful, but WITHOUT
10: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12: * details. You should have received a copy of the GNU General Public License
13: * along with this program. If not, see <http://www.gnu.org/licenses/>.
14: */
15: package cz.cvut.kbss.jsonld.deserialization;
16:
17: import cz.cvut.kbss.jsonld.common.BeanAnnotationProcessor;
18: import cz.cvut.kbss.jsonld.common.BeanClassProcessor;
19: import cz.cvut.kbss.jsonld.exception.JsonLdDeserializationException;
20:
21: import java.lang.reflect.Field;
22: import java.util.Collection;
23: import java.util.Map;
24: import java.util.Optional;
25:
26: class SingularObjectContext<T> extends InstanceContext<T> {
27:
28: private final Map<String, Field> fieldMap;
29:
30: SingularObjectContext(T instance, Map<String, Field> fieldMap, Map<String, Object> knownInstances) {
31: super(instance, knownInstances);
32: this.fieldMap = fieldMap;
33: }
34:
35: @Override
36: Field getFieldForProperty(String property) {
37: return fieldMap.get(property);
38: }
39:
40: @Override
41: void setFieldValue(Field field, Object value) {
42:• assert !(instance instanceof Collection);
43: final Optional<Object> toSet = resolveAssignableValue(field.getType(), value);
44:• if (!toSet.isPresent()) {
45: throw valueTypeMismatch(value, field);
46: }
47: BeanClassProcessor.setFieldValue(field, instance, toSet.get());
48: }
49:
50: private JsonLdDeserializationException valueTypeMismatch(Object value, Field field) {
51: final Object attemptedValue = knownInstances.getOrDefault(value.toString(), value);
52: return new JsonLdDeserializationException(
53: "Type mismatch. Cannot set value " + attemptedValue + " of type " + attemptedValue.getClass() +
54: " on field " + field);
55: }
56:
57: @Override
58: boolean isPropertyMapped(String property) {
59: return fieldMap.containsKey(property) || hasPropertiesField();
60: }
61:
62: @Override
63: boolean supports(String property) {
64: if (!isPropertyMapped(property)) {
65: return false;
66: }
67: return !fieldMap.containsKey(property) || BeanAnnotationProcessor.isWriteable(fieldMap.get(property));
68: }
69: }